#include "Agent.h"
#include <iostream>

using namespace std;

Agent::Agent(std::string ip, int port)
{
	sock = SocketClient(ip.c_str(), port);
}

Agent::~Agent()
{
	sock.closeSock();
}

void Agent::sendProto(std::string msg)
{
	try {
		char id = _proto[msg];
		sock.sendMsg((void*)(&id), 1);
	}
	catch(exception e) {
		cout << "Unknown message" << endl;
	}
}

void Agent::sendString(const char *buf, int size)
{
	sock.sendMsg(buf, size);
}

void Agent::sendInt(int n)
{
	sock.send4((unsigned long)n);
}
 
std::string Agent::getProto()
{
	char id;
	sock.readMsg(&id, 1);
	map<string, char>::iterator it;
	for(it = _proto._messages.begin(); it != _proto._messages.end(); ++it)
	{
		if(it->second == id)
			return it->first;
	}
	return "unknown";
}

int Agent::getInt()
{
	long n;
	sock.read4(&n);
	return n;
}

std::string Agent::getString(int size, int bufsize)
{
	char s[bufsize];
	sock.readMsg(s, size);
	s[size] = 0;
	return s;
}
